package com.cssw.fyzb.busi.api.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cssw.fyzb.busi.config.TpsClient;
import com.cssw.fyzb.busi.model.tps.*;
import com.cssw.fyzb.busi.service.pay.PayService;
import com.cssw.fyzb.busi.service.pay.QuickPayService;
import com.cssw.fyzb.busi.service.user.UserService;
import com.cssw.fyzb.busi.util.BizUtil;
import com.cssw.fyzb.busi.util.MapUtil;
import com.cssw.fyzb.core.exception.BizException;
import com.cssw.fyzb.core.model.dodb.PayOrder;
import com.cssw.fyzb.core.model.dodb.QuickRequestLog;
import com.cssw.fyzb.core.model.dodb.User;
import com.cssw.fyzb.core.model.vo.pay.QuickPayVo;
import com.cssw.fyzb.core.util.StringUtil;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplecache.SimpleCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: yangyiqun
 * @Date: 2020/7/14 22:10
 */

@Function(description = "快捷签约信息", parameters = {
        @Parameter(name = "userId", type = Type.String, description = "用户标识", required = true),
        @Parameter(name = "orderNo", type = Type.String, description = "银行编码", required = true),
        @Parameter(name = "verifyCode", type = Type.String, description = "校验编码", required = true)
})
@Component
public class QuickPaySmsOk implements Action {

    private static final Logger logger = LoggerFactory.getLogger(QuickPaySmsOk.class);

    @Autowired
    private TpsClient tpsClient;

    @Autowired
    private QuickPayService quickPayService;

    @Autowired
    private UserService userService;

    @Autowired
    private SimpleCache simpleCache;

    @Autowired
    private PayService payService;

    @Override
    public Response execute(Request request) throws Exception {
        Long userId = request.getLong("userId");
        String orderNo = request.getString("orderNo");
        String verifyCode = request.getString("verifyCode");

        try {
            PayOrder payOrder = payService.getByTradeNo(orderNo);
            if (null == payOrder || !PayOrder.STATUS_PAYING.equals(payOrder.getStatus())){
                BizUtil.exception("支付信息不正确！");
            }

            Tf56PayQuickPaySmsDataVo dataVo = tf56PayQuickPaySms(verifyCode, userId);

            payService.updatePayStatus(payOrder, PayOrder.STATUS_PAY_SEND);
            payService.updateUserPay(userId, orderNo, payOrder.getPayWay());
            Map map = new HashMap();
            map.put("orderNo", orderNo);
            return Response.success().put("data", map);
        } catch (Exception e){
            if (e instanceof BizException) {
                BizException be = (BizException) e;
                return Response.fail(be.getErrMsg(), be.getErrCode());
            }
            logger.error("", e);
            return Response.fail("支付失败！");
        }
    }

    private Tf56PayQuickPaySmsDataVo tf56PayQuickPaySms(String verifyCode, Long userId){

        String quickPayStr = simpleCache.get("TF56PAYQUICKPAY_" + userId);
        if (StringUtil.isEmpty(quickPayStr)){
            BizUtil.exception("支付超时，请重试！");
        }

        QuickPayVo quickPayVo = JSON.parseObject(quickPayStr, QuickPayVo.class);

        Map<String, Object> param = new HashMap<>();
        param.put("busiNo", quickPayVo.getBusiNo());
        param.put("verifyCode", verifyCode);

        Tf56PayQuickPaySmsVo vo = null;
        try {
            vo = tpsClient.tf56PayQuickPaySms(quickPayVo.getBusiNo(), verifyCode);
        } catch (Exception e){
            if (e instanceof BizException) {
                BizException be = (BizException) e;
                saveQuickRequestLog(userId, quickPayVo.getOrderNo(), quickPayVo.getBusiNo(), String.valueOf(be.getErrCode()), be.getErrMsg(), param, vo);
                throw be;
            } else {
                saveQuickRequestLog(userId, quickPayVo.getOrderNo(), quickPayVo.getBusiNo(), "-99", e.getMessage(), param, vo);
            }
            BizUtil.exception("快捷支付失败！");
        }
        if (!(isSuccess(vo))) {
            logger.error(">>>>" + vo);
            saveQuickRequestLog(userId, quickPayVo.getOrderNo(), quickPayVo.getBusiNo(), getErrorCode(vo), getErrorMsg(vo), param, vo);

            //如果业务不成功，则返回第三方的错误信息
            if (!"GPBIZ_00".equals(vo.getBiz_code())) {
                BizUtil.exception(vo.getBiz_msg());
            }

            BizUtil.exception("快捷支付失败！");
        }

        Tf56PayQuickPaySmsDataVo dataVo = vo.getDataVo();
        if (null == dataVo) {
            saveQuickRequestLog(userId, quickPayVo.getOrderNo(), quickPayVo.getBusiNo(), "-1", "数据对象为空", param, vo);
            BizUtil.exception("快捷支付失败！");
        }

        saveQuickRequestLog(userId, quickPayVo.getOrderNo(), quickPayVo.getBusiNo(), getErrorCode(vo), getErrorMsg(vo), param, vo);

        quickPayService.saveQuickPayOrder(quickPayVo.getUserId(), quickPayVo.getCertCode(), quickPayVo.getBusiType(),
                quickPayVo.getAmount(), quickPayVo.getGoodsName(), quickPayVo.getGoodsDesc(), quickPayVo.getOrderNo(),
                quickPayVo.getBusiNo());

        return dataVo;
    }


    private void saveQuickRequestLog(Long userId, String orderNo, String busiNo, String errorCode, String errorMsg, Map reqParam, Tf56PayQuickPaySmsVo vo) {
        if (errorMsg != null && errorMsg.length() > 200) {
            errorMsg = errorMsg.substring(0, 200);
        }
        quickPayService.saveQuickRequestLog(userId, orderNo, busiNo, QuickRequestLog.TYPE_PAY, errorCode, errorMsg, JSON.toJSONString(reqParam), JSON.toJSONString(vo));
    }


    private boolean isSuccess(Tf56PayQuickPaySmsVo vo) {
        return "GP_00".equals(vo.getCode()) && "GPBIZ_00".equals(vo.getBiz_code());
    }


    private String getErrorCode(Tf56PayQuickPaySmsVo vo) {
        if (!"GP_00".equals(vo.getCode())) {
            return vo.getCode();
        }
        if (!"GPBIZ_00".equals(vo.getBiz_code())) {
            return vo.getBiz_code();
        }

        return "0";
    }

    private String getErrorMsg(Tf56PayQuickPaySmsVo vo) {
        if (!"GP_00".equals(vo.getCode())) {
            return vo.getMsg();
        }
        if (!"GPBIZ_00".equals(vo.getBiz_code())) {
            return vo.getBiz_msg();
        }

        return "success";
    }
}